﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IntraVision.Web;

namespace Model
{
    partial class User : IUser
    {
        #region IUser Members

        string IUser.Name
        {
            get { return FIO; }
        }

        public bool HasAnyPermission(string permissions)
        {
            foreach (var p in permissions.Split(','))
                if (this.HasPermission(p.Trim()))
                    return true;
            return false;
        }

        public bool HasAllPermissions(string permissions)
        {
            foreach(var p in permissions.Split(','))
                if (!this.HasPermission(p.Trim()))
                    return false;
            return true;
        }

        public bool HasPermission(string permission)
        {
            if (permission.ToLower() == "isadmin") return true;
            if (permission.ToLower() == "finance") return this.Login.ToLower().Equals("TWO\\repin".ToLower(), StringComparison.InvariantCulture);
            return (this.UserPermissions.Any(up => up.Permission.Alias.ToLower() == permission.ToLower()));
        }
        #endregion

        public bool CanEditOrder(NotarialServiceDataContext dc, Order order)
        {
            return this.HasAnyPermission("UnlockOrder,EditRows")
                              || (from u in dc.Users
                                  join up in dc.UserPermissions on u.Id equals up.UserId
                                  join op in dc.OrderEditPermissions on up.PermissionId equals op.PermissionId
                                  where (this.Id == u.Id) && (order.StatusId == op.StatusId)
                                    && (
                                            (!op.IsOnlyComplicated && !op.IsOnlySimple)
                                            || (op.IsOnlyComplicated && order.IsComplicated)
                                            || (op.IsOnlySimple && !order.IsComplicated)
                                        )
                                  select u.Id
                                  ).Any();
        }

        public string FullName
        { 
            get { return String.Format("{0} {1} {2}", this.LastName, this.Name, this.PatronymicName); } 
        }
        public string FIO
        {
            get
            {
                var sb = new StringBuilder();
                if (!String.IsNullOrEmpty(this.LastName)) { sb.Append(this.LastName); sb.Append(" "); }
                if (this.Name != null && !String.IsNullOrEmpty(this.Name.Trim())) { sb.Append(this.Name.TrimStart()[0]); sb.Append(". "); }
                if (this.PatronymicName != null && !String.IsNullOrEmpty(this.PatronymicName.Trim())) { sb.Append(this.PatronymicName.TrimStart()[0]); sb.Append(". "); }
                return sb.ToString();
            }
        }        
    }
}
